<template>
  <div class="inventory-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>库存管理</span>
          <div class="header-actions">
      
          </div>
        </div>
      </template>
      <el-table
      :data="tableData"
      border
      stripe
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
    >
      <el-table-column prop="deviceName" label="设备名称" width="180" />
      <el-table-column prop="inventory" label="库存" width="150" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑设备' : '新增设备'"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="formData.deviceName" />
        </el-form-item>
        <el-form-item label="库存" prop="model">
          <el-input v-model="formData.inventory" />
        </el-form-item>
    
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as api from '@/api/device'
import { listCategory } from '@/api/category'

// 数据相关
const tableData = ref([])
const categories = ref([])
const loading = ref(false)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formData = ref({
  deviceName: '',
  model: '',
  specification: '',
  manufacturer: '',
  purchaseDate: '',
  warrantyMonths: 12,
  categoryId: ''
})
const formRef = ref(null)

// 表单验证规则
const formRules = {
  deviceName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择设备分类', trigger: 'change' }]
}

// 分类ID转名称
const categoryFormatter = (value) => {

  const category = categories.value.find((item) => item.id == value)
  return category ? category.categoryName : value
}

// 获取设备数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      keyword: searchKeyword.value
    }
    const res = await api.list(params)
    tableData.value = res || res.list || res
  } catch (error) {
    ElMessage.error('获取设备列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    const res = await listCategory()
    categories.value = res 
  } catch (error) {
    ElMessage.error('获取分类列表失败: ' + error.message)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 新增
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    deviceName: '',
    model: '',
    specification: '',
    manufacturer: '',
    purchaseDate: '',
    warrantyMonths: 12,
    categoryId: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该设备吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await api.del(row.id)
        ElMessage.success('删除成功')
        fetchData()
      } catch (error) {
        ElMessage.error('删除失败: ' + error.message)
      }
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await api.update(formData.value)
      ElMessage.success('更新成功')
    } else {
      await api.add(formData.value)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    if (!error.message) return // 验证未通过
    ElMessage.error((isEdit.value ? '更新' : '新增') + '失败: ' + error.message)
  }
}

// 初始化数据
onMounted(() => {
  fetchData()
  fetchCategories()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}
</style>